package abc.datasource;

import com.baomidou.dynamic.datasource.annotation.DS;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Aspect
@Order(1)
@Component
public class DataSourceAspect {
    @Pointcut("@annotation(com.baomidou.dynamic.datasource.annotation.DS)"
            + "|| @within(com.baomidou.dynamic.datasource.annotation.DS)"
            +"|| @annotation(abc.datasource.DataSource)"
            + "|| @within(abc.datasource.DataSource)")
    public void dsPc() {
        System.out.println("DataSourceAspect running......");
    }

    @Around("dsPc()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        DS dataSource = getDS(point);

        if (Objects.nonNull(dataSource)) {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value());
        }
        else {
            DataSource ds = getDataSource(point);
            if(Objects.nonNull(dataSource)) {
                DynamicDataSourceContextHolder.setDataSourceType(ds.dataSourceName());
            }
        }

        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public DS getDS(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DS dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DS.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource;
        }
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DS.class);
    }


    /**
     * 获取需要切换的数据源
     */
    public DataSource getDataSource(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource;
        }
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }
}
